define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'bootstrap-select-lang', 'selectpage'], function ($, undefined, Backend, Table, Form, undefined, undefined) {
    var Controller = {
        index: function () {

            Table.api.init({
                extend: {
                    index_url: 'fastflow/flow/flow/index' + location.search,
                    add_url: 'fastflow/flow/flow/add',
                    edit_url: 'fastflow/flow/flow/edit',
                    del_url: 'fastflow/flow/flow/del',
                    multi_url: 'fastflow/flow/flow/multi',
                    import_url: 'fastflow/flow/flow/import',
                    table: 'wf_flow',
                }
            });

            var table = $("#table");

            
            table.on('post-common-search.bs.table', function (event, table) {
                var form = $("form", table.$commonsearch);
                $("input[name='createuser_id']", form).addClass("selectpage").data("source", "fastflow/flow/flow/getSelectpageWorkers?scope=1").data("primaryKey", "id").data("field", "createuser_id").data("orderBy", "id asc");
                Form.events.selectpage(form);
            });

            
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                rowStyle: function (row, index) {
                    return {
                        css: {
                            height: '60px'
                        }
                    };
                },
                columns: [
                    [
                        {field: 'id', title: __('Id'), sortable: true,},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {field: 'bill_name', title: __('BillName'), formatter: Controller.api.formatter.normal},
                        {field: 'bill', title: __('Bill'), formatter: Table.api.formatter.normal},
                        {
                            field: 'description',
                            title: __('Description'),
                            operate: 'LIKE',
                            formatter: Table.api.formatter.content
                        },
                        {
                            field: 'createuser_id',
                            title: __('Createuser_id'),
                            formatter: Table.api.formatter.search,
                            visible: false
                        },
                        {field: 'createusername', title: __('Createuser_name'), operate: false},
                        {
                            field: 'createtime',
                            title: __('Createtime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'status',
                            title: __('Status'),
                            searchList: {"0": __('Status 0'), "1": __('Status 1')},
                            formatter: Controller.api.formatter.status,
                            events: Controller.api.events.status,
                            custom: {0: 'success', 1: 'danger'}
                        },
                        {
                            field: 'isrun',
                            title: __('Designer'),
                            operate: false,
                            table: table,
                            events: Controller.api.events.opendesigner,
                            formatter: Controller.api.formatter.designerbtn
                        },
                        {field: '', title: __('FlowAuth'),operate: false, formatter: Controller.api.formatter.flowauth},
                        {
                            field: 'operate',
                            title: __('EDIT'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        },
                        {field: 'remark', title: __('Remark'), operate: false, formatter: Table.api.formatter.content},
                    ]
                ]
            });

            
            Table.api.bindevent(table);

            $('body', document).on('keyup', function(e) {
                if (e.which === 27) {
                    return false;
                }
            });
        },
        add: function () {
            Form.api.bindevent($("form[role=form]"));
        },
        edit: function () {
            Form.api.bindevent($("form[role=form]"));
        },
        designer: function () {
            if ($(window).width() < 700){
                $('body').html('<div class="alert alert-danger">请使用电脑进行流程设计或确保设计器窗口宽度大于700像素</div>');
                return;
            }
            require(['fastflow'], function (fastflow) {
                fastflow.run(Config.flow.graph, Config.flow.id, config = {saveAction: 'fastflow/flow/Flow/saveGraph'});
                $(document).on("fa.event.appendfieldlist", ".btn-append", function (e, obj) {
                    Form.events.selectpage(obj);
                    fastflow.createStepSelectOption();
                });
            });

            Form.api.bindevent($("form[role=form]"));
            $('#c-worker').data("params", function (obj) {
                return {"scope": $('#c-scope').val()};
            });
        },
        detail:function(){
            //调整窗口大小---
            var footer = $('.footer');
            $('.layui-layer-content', parent.document).after(footer);
            footer.css('display','block');
            var dialogHeight = $('.layui-layer-iframe',parent.document).height();
            $('.layui-layer-iframe',parent.document).height(dialogHeight - 53);
            var iframeHeight = $('.layui-layer-content iframe', parent.document).height();
            $('.layui-layer-content iframe', parent.document).height(iframeHeight - 53);
            $('.layui-layer-resize', parent.document).css('bottom','-53px');
            //---调整窗口大小

            Controller.api.bindPrintEvent();
            //不放在bindPrintEvent方法内，防止反复弹出打印页
            $('.bill-print',parent.document).click(function () {
                Controller.api.print('bill');
            });
            $('.merge-print',parent.document).click(function () {
                Controller.api.mergePrint();
            });
            $('.export-word',parent.document).click(function () {
                Controller.api.exportWord();
            });

            var index = layer.load();
            $.ajax({
                type: "get",
                url: Config.controller_url + "/edit",
                data: {ids: Config.bill_id, way: 'detail'},
                success: function (data) {
                    $('#fastflow-right-content #bill-edit').append($('#edit-form',data));
                    $('[name^="row"]',$('#edit-form','#fastflow-right-content')).attr('disabled','disabled');
                    $('button',$('#edit-form','#fastflow-right-content')).addClass('hidden');
                    Form.api.bindevent($("#edit-form"));
                    $('a.btn',$('#edit-form','#fastflow-right-content')).addClass('hidden');
                    $(document).on("fa.event.appendfieldlist", function(){
                        $('textarea[disabled="disabled"]').closest('.form-group').find('.btn-remove').addClass('hidden');
                        $('textarea[disabled="disabled"]').closest('.form-group').find('.btn-dragsort').addClass('hidden');
                        $('textarea[disabled="disabled"]').closest('.form-group').find('.btn-append').addClass('hidden');
                        $('textarea[disabled="disabled"]').closest('.form-group').find('input').attr('disabled','disabled');
                    });
                    layer.close(index);
                },
                error:function (e) {
                    layer.close(index);
                }
            });
        },
        viewer:function(){

        },
        auth:function(){
            let startRules = Config.startRules;
            if (startRules != undefined) {
                $('textarea[name="start"]').val(JSON.stringify(startRules));
                $('textarea[name="start"]').trigger("fa.event.refreshfieldlist");
            }
            let editRules = Config.editRules;
            if (editRules != undefined) {
                $('textarea[name="edit"]').val(JSON.stringify(editRules));
                $('textarea[name="edit"]').trigger("fa.event.refreshfieldlist");
            }
            $(document).on("fa.event.appendfieldlist", ".btn-new-start-rule", function (e, obj) {
                let that = this;
                Form.events.selectpicker(obj);
                Fast.api.ajax({
                    url: "fastflow/flow/flow/getStartAuthSelectOptionData",
                    data: '',
                }, function (data, ret) {
                    let ruleBehavior = $(obj).find("select.rule-behavior");
                    let ruleScope = $(obj).find("select.rule-scope");
                    let ruleControl = $(obj).find("select.rule-control");
                    Controller.api.buildoptions(ruleBehavior, data['behavior'], 'table', [ruleBehavior.attr('value')]);
                    Controller.api.buildoptions(ruleScope, data['scope'], 'table', [ruleScope.attr('value')]);
                    Controller.api.buildoptions(ruleControl, data['control'], 'table', [ruleControl.attr('value')]);
                    return false;
                });
            });
            $(document).on('change', "select.rule-scope", function () {
                let that = this;
                workerSelectPage = $(that).closest("tr").find("input.rule-worker");
                workerSelectPage.data('params', function (obj) {
                    return {"scope": $(that).val()};
                });

                Form.events.selectpage($(that).closest("tr"));
                workerSelectPage.selectPageClear();
            });
            $(document).on("fa.event.appendfieldlist", ".btn-new-edit-rule", function (e, obj) {
                let that = this;
                Form.events.selectpicker(obj);
                Fast.api.ajax({
                    url: "fastflow/flow/flow/getEditAuthSelectOptionData",
                    data: {"flowid":Config.flow['id']},
                }, function (data, ret) {
                    let ruleBehavior = $(obj).find("select.rule-behavior");
                    let ruleSteps = $(obj).find("select.rule-steps");
                    let ruleControl = $(obj).find("select.rule-control");
                    Controller.api.buildoptions(ruleBehavior, data['behavior'], 'table', [ruleBehavior.attr('value')]);
                    Controller.api.buildoptions(ruleSteps, data['steps'], 'table', ruleSteps.attr('value').split(','));
                    Controller.api.buildoptions(ruleControl, data['control'], 'table', [ruleControl.attr('value')]);
                    return false;
                });
                Fast.api.ajax({
                    url: "fastflow/flow/flow/getFieldsWithComment",
                    data: {table: Config.flow['bill']},
                }, function (data, ret) {
                    let ruleFields = $(obj).find("select.rule-fields");
                    Controller.api.buildoptions(ruleFields, data, 'fields', ruleFields.attr('value').split(','));
                    return false;
                });
            });


            Form.api.bindevent($("form[role=form]"));
        },
        api: {
            buildoptions: function (select, data, type, value = null) {
                var html = '';
                data.forEach(function (e) {
                    if (type == 'fields') {
                        let selected = $.inArray(e['field'].toString(), value) != -1 ? 'selected' : '';
                        html += "<option value='" + e['field'] + "' " + selected + ">" + e['field'] + '(' + e['comment'] + ')' + "</option>";
                    } else if (type == 'table') {
                        let selected = $.inArray(e['value'].toString(), value) != -1 ? 'selected' : '';
                        html += "<option value='" + e['value'] + "' " + selected + ">" + e['name'] + "</option>";
                    } else if (type == 'item') {
                        let selected = $.inArray(e.toString(), value) != -1 ? 'selected' : '';
                        html += "<option value='" + e + "' " + selected + ">" + e + "</option>";
                    }
                });
                $(select).html(html);
                if (select.data("selectpicker")) {
                    select.selectpicker('refresh');
                }
                select.trigger("change");
            },
            bindevent: function () {
            },
            bindPrintEvent:function(){
                $('.table-print').click(function () {
                    Controller.api.print('table');
                });
                $('.timeline-print').click(function () {
                    Controller.api.print('timeline');
                });
            },
            print:function(type){
                $('.' + type + '-print').addClass('hidden');
                if (type === 'table' || type === 'timeline'){
                    $('.detail-table').css('table-layout','unset');
                    //提取资料地址
                    var fileSpan = $('.flow-file',$('.' + type));
                    $(fileSpan).each(function (index, item) {
                        var fileUrl = $('a',$(item)).attr('href');
                        var fileName =  $('a',$(item)).html();
                        $(item).html("<label data-name='"+ fileName +"'>"+Config.domain + "<span>" + fileUrl+ "</span>" +"</label>");
                    });
                }
                if (type == 'bill'){
                    $('.bill-legend').removeClass('hidden');
                }
                var html = $('body', window.document).html();
                var printStart = "<!--" + type +"PrintStart-->";
                var printEnd = "<!--" + type +"PrintEnd-->";
                var printHtml = html.substr(html.indexOf(printStart));
                printHtml = printHtml.substring(0,printHtml.indexOf(printEnd));
                window.document.body.innerHTML=printHtml;
                window.print();
                //还原
                window.document.body.innerHTML = html;
                if (type === 'table' || type === 'timeline'){
                    $('.detail-table').css('table-layout','fixed');
                    //还原资料下载按钮
                    var fileSpan = $('.flow-file',$('.' + type));

                    $(fileSpan).each(function (index, item) {
                        var fileLable = $('label',$(item));
                        var fileName = fileLable.data('name');
                        var fileUrl = $('span',fileLable).html();
                        $(item).html("<a href='"+ fileUrl +"' class='btn btn-info-light btn-xs'>"+ fileName +"</a>");
                    });

                }
                $('.' + type + '-print').removeClass('hidden');
                $('.bill-legend').addClass('hidden');
                Controller.api.bindPrintEvent();
            },
            mergePrint:function(){
                $('.table-print').addClass('hidden');
                $('.detail-table').css('table-layout','unset');
                //提取资料地址
                var fileSpan = $('.flow-file',$('.table'));
                $(fileSpan).each(function (index, item) {
                    var fileUrl = $('a',$(item)).attr('href');
                    var fileName =  $('a',$(item)).html();
                    $(item).html("<label data-name='"+ fileName +"'>"+Config.domain + "<span>" + fileUrl+ "</span>" +"</label>");
                });

                var html = $('body', window.document).html();
                //table
                var tableStart = "<!--tablePrintStart-->";
                var tableEnd = "<!--tablePrintEnd-->";
                var tableHtml = html.substr(html.indexOf(tableStart));
                tableHtml = tableHtml.substring(0,tableHtml.indexOf(tableEnd));
                //bill
                var billStart = "<!--billPrintStart-->";
                var billEnd = "<!--billPrintEnd-->";
                var billHtml = html.substr(html.indexOf(billStart));
                billHtml = billHtml.substring(0,billHtml.indexOf(billEnd));

                window.document.body.innerHTML = tableHtml + billHtml;
                window.print();
                //还原
                window.document.body.innerHTML = html;
                $('.detail-table').css('table-layout','fixed');
                //还原资料下载按钮
                var fileSpan = $('.flow-file',$('.table'));

                $(fileSpan).each(function (index, item) {
                    var fileLable = $('label',$(item));
                    var fileName = fileLable.data('name');
                    var fileUrl = $('span',fileLable).html();
                    $(item).html("<a href='"+ fileUrl +"' class='btn btn-info-light btn-xs'>"+ fileName +"</a>");
                });
                $('.table-print').removeClass('hidden');
                Controller.api.bindPrintEvent();
            },
            exportWord:function(){
                $.ajax({
                    type: "get",
                    url: "fastflow/flow/flow/exportWord",
                    data: {
                        bill: Config.bill,
                        bill_id: Config.bill_id
                    },
                    success: function (data) {
                        if (data['code'] == 1) {
                            let url = data['data']['url'];
                            let a = document.createElement('a');
                            a.href = url;
                            a.download = data['data']['fileName'] + '审批详情.docx';
                            a.click();
                            delete a;
                        } else if (data['code'] == 0) {
                            Toastr.error(data['msg']);
                        }
                    },
                    error:function (e) {}
                });
            },
            formatter: {
                status: function (value, row, index) {
                    return '<a href="javascript:;" class="btn btn-xs btn-status ' + (value == 0 ? 'btn-danger' : 'btn-success') + '" title="点击切换" data-table-id="table" style="margin-right: 4px;font-size: 90%;">' + (value == 0 ? '禁用(点击启用)' : '启用(点击禁用)') + '</a>';
                },
                designerbtn: function (value, row, index) {
                    let html = '';
                    if (value == 0) {
                        html = '<a href="fastflow/flow/flow/designer?flow_id=' + row['id'] + '" class="btn btn-xs btn-info btn-dialog" title="流程设计" data-table-id="table" style="margin-right: 4px;font-size: 90%;"><i class="fa fa-list" style="margin-right: 4px;"></i>流程设计</a>';
                    } else {
                        html = '<a href="javascript:;" class="btn btn-xs btn-warning" style="font-size: 90%"><i class="fa fa-play-circle" style="margin-right: 4px;"></i>运行中....</a>';
                    }

                    return html;

                },
                flowauth: function (value, row, index) {
                    return '<a href="fastflow/flow/flow/auth?flow_id=' + row['id'] + '" class="btn btn-xs btn-danger btn-dialog"  data-toggle="tooltip" title="流程权限配置" data-table-id="table"  data-original-title="流程权限配置" style="font-size: 90%"><i class="fa fa-lock" style="margin-right: 4px;"></i>权限配置</a>';
                },
                normal: function (value, row, index) {
                    return '<a href="javascript:;" class="searchit" data-toggle="tooltip" title="' + __('Click to search %s', row["bill_name"]) + '" data-field="bill" data-value="' + row["bill"] + '">' + value + '</a>';
                },
            },
            events: {
                status: {
                    'click .btn-status': function (e, value, row, index) {
                        e.stopPropagation();
                        e.preventDefault();
                        var that = this;
                        var top = $(that).offset().top - $(window).scrollTop();
                        var left = $(that).offset().left - $(window).scrollLeft() - 260;
                        if (top + 154 > $(window).height()) {
                            top = top - 154;
                        }
                        if ($(window).width() < 480) {
                            top = left = undefined;
                        }
                        var table = $(that).closest('table');
                        if (value == 0) {
                            $(that).data('params', {'status': 1});
                            Table.api.multi(undefined, row['id'], table, that);
                        } else {
                            $(that).data('params', {'status': 0});
                            Layer.confirm(
                                __('确定禁用吗?'),
                                {
                                    icon: 3,
                                    title: __('Warning'),
                                    offset: [top, left],
                                    shadeClose: true,
                                    btn: [__('OK'), __('Cancel')]
                                },
                                function (index) {
                                    var options = table.bootstrapTable('getOptions');
                                    Table.api.multi(undefined, row['id'], table, that);
                                    Layer.close(index);
                                }
                            );
                        }

                    }
                },
                opendesigner: {
                    'click .btn-dialog': function (e, value, row, index) {
                        e.stopPropagation();
                        e.preventDefault();
                        var table = $(this).closest('table');
                        var options = table.bootstrapTable('getOptions');
                        var ids = row[options.pk];
                        row = $.extend({}, row ? row : {}, {ids: ids});
                        $(this).data('area', ['100%', '100%']);
                        Fast.api.open(Table.api.replaceurl($(this).attr('href'), row, table), $(this).data("original-title") || $(this).attr("title"), $(this).data() || {});
                    }
                }
            }
        }
    };
    return Controller;
});
